// API缓存服务
class ApiCache {
  constructor() {
    this.cache = new Map()
    this.cacheExpiry = new Map()
    this.defaultExpiry = 5 * 60 * 1000 // 5分钟默认过期时间
  }

  // 设置缓存
  set(key, value, expiry = this.defaultExpiry) {
    this.cache.set(key, value)
    this.cacheExpiry.set(key, Date.now() + expiry)
  }

  // 获取缓存
  get(key) {
    if (!this.cache.has(key)) {
      return null
    }

    const expiry = this.cacheExpiry.get(key)
    if (Date.now() > expiry) {
      this.delete(key)
      return null
    }

    return this.cache.get(key)
  }

  // 删除缓存
  delete(key) {
    this.cache.delete(key)
    this.cacheExpiry.delete(key)
  }

  // 清空所有缓存
  clear() {
    this.cache.clear()
    this.cacheExpiry.clear()
  }

  // 清空特定前缀的缓存
  clearByPrefix(prefix) {
    for (const key of this.cache.keys()) {
      if (key.startsWith(prefix)) {
        this.delete(key)
      }
    }
  }

  // 检查缓存是否存在且未过期
  has(key) {
    return this.get(key) !== null
  }

  // 获取缓存大小
  size() {
    return this.cache.size
  }
}

// 创建全局缓存实例
export const apiCache = new ApiCache()

// 缓存键常量
export const CACHE_KEYS = {
  USERS: 'users',
  ROLES: 'roles',
  PERMISSIONS: 'permissions',
  USER_ROLES: 'user_roles',
  ROLE_PERMISSIONS: 'role_permissions'
}

// 带缓存的API请求函数
export async function cachedRequest(requestFn, cacheKey, expiry = 5 * 60 * 1000) {
  // 检查缓存
  const cachedData = apiCache.get(cacheKey)
  if (cachedData) {
    return cachedData
  }

  // 执行请求
  const data = await requestFn()
  
  // 缓存结果
  if (data) {
    apiCache.set(cacheKey, data, expiry)
  }

  return data
}

// 批量请求优化函数
export async function batchRequest(requests, batchSize = 5) {
  const results = []
  
  for (let i = 0; i < requests.length; i += batchSize) {
    const batch = requests.slice(i, i + batchSize)
    const batchResults = await Promise.allSettled(batch)
    
    results.push(...batchResults.map(result => 
      result.status === 'fulfilled' ? result.value : null
    ))
  }
  
  return results
}

// 防抖函数
export function debounce(func, wait) {
  let timeout
  return function executedFunction(...args) {
    const later = () => {
      clearTimeout(timeout)
      func(...args)
    }
    clearTimeout(timeout)
    timeout = setTimeout(later, wait)
  }
}

// 节流函数
export function throttle(func, limit) {
  let inThrottle
  return function() {
    const args = arguments
    const context = this
    if (!inThrottle) {
      func.apply(context, args)
      inThrottle = true
      setTimeout(() => inThrottle = false, limit)
    }
  }
}

export default apiCache 